package org.blim.blackdawn;

import java.util.ArrayList;
import java.util.List;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import org.blim.blackdawn.graph.Renderer;
import org.blim.blackdawn.graph.SceneGraph;
import org.blim.blackdawn.model.Model;
import org.blim.blackdawn.model.TriangleArray;
import org.blim.blackdawn.shader.DiffuseArrayShader;
import org.blim.blackdawn.shader.Shader;

import android.content.Context;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;

public class GameRenderer implements GLSurfaceView.Renderer {
	
	//private static final String TAG = GameRenderer.class.getSimpleName();

	private final Context mContext;

	private SceneGraph mSceneGraph;
	private List<Model> mDefinitions;

	private Shader<TriangleArray> mArrayShader;

	/**
	 * Initialize the model data.
	 */
	public GameRenderer(final Context activityContext) {
		mContext = activityContext;
	}

	@Override
	public void onSurfaceCreated(GL10 glUnused, EGLConfig config) {
		mArrayShader = new DiffuseArrayShader(mContext);
		mSceneGraph = new SceneGraph();
		mDefinitions = new ArrayList<Model>();
		
		// Set the background clear color to black.
		GLES20.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

		// Use culling to remove back faces.
		GLES20.glEnable(GLES20.GL_CULL_FACE);

		// Enable depth testing
		GLES20.glEnable(GLES20.GL_DEPTH_TEST);

		// Set the view matrix. This matrix can be said to represent the camera
		// position.
		Matrix.setLookAtM(mSceneGraph.mView, 0,
				0.0f, 0.0f, -0.5f,   // eye vertex
				0.0f, 0.0f, -5.0f,   // look vector
				0.0f, 1.0f, 0.0f     // orientation vector
		);

		Demo.createScene(mContext, mSceneGraph, mDefinitions, mArrayShader);
	}

	@Override
	public void onSurfaceChanged(GL10 glUnused, int width, int height) {
		GLES20.glViewport(0, 0, width, height);

		final float ratio = (float) width / height;
		final float left = -ratio;
		final float right = ratio;
		final float bottom = -1.0f;
		final float top = 1.0f;
		final float near = 1.0f;
		final float far = 10.0f;

		Matrix.frustumM(mSceneGraph.mProjection, 0,
				left, right, bottom, top, near, far);
	}

	@Override
	public void onDrawFrame(GL10 glUnused) {
		GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);

		Renderer glRender = new Renderer(mSceneGraph);
		glRender.render();

	}
    
}
